package com.nmf.site.biz.pic;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.nmf.pc.enums.RspStatus;
import com.nmf.pc.vo.ReturnResult;
import com.nmf.site.biz.pay.ali.sign.MD5Util;
import com.nmf.site.common.config.Global;
import com.nmf.site.common.utils.IdGenerater;

@Controller
public class PcImgController {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	IdGenerater idGenerater;
	@RequestMapping(value = { "${adminPath}/pic/img/upload" }, method = { RequestMethod.POST })
	@ResponseBody
	public ReturnResult add(HttpServletRequest request, HttpServletResponse response) {
		DefaultMultipartHttpServletRequest defaultMultipartHttpServletRequest = (DefaultMultipartHttpServletRequest)request;
		
		MultiValueMap<String, MultipartFile> mmap = defaultMultipartHttpServletRequest.getMultiFileMap();
		ReturnResult returnResult = new ReturnResult();
		if(!mmap.isEmpty()) {
			for (String key : mmap.keySet()) {
				List<MultipartFile> multipartFileList = mmap.get(key);
				String path = System.currentTimeMillis()+"";
				for(MultipartFile multipartFile : multipartFileList) {
					String oname = MD5Util.MD5(multipartFile.getOriginalFilename())+"."+multipartFile.getOriginalFilename().split("\\.")[1];
					String fileFolder = path+File.separator+idGenerater.genClsNo("pic")+File.separator;
					File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL+ fileFolder+ oname);
					if(!file.getParentFile().exists()) {
						file.getParentFile().mkdirs();
					}
					try {
						FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(file));
						String xx = Global.USERFILES_BASE_URL+fileFolder;
						xx = xx.replace("\\", "/").replace("//", "/");
						returnResult.setData(xx+file.getName());
					} catch (Exception e) {
						logger.error("",e);
						returnResult.setStatus(RspStatus.FAILED.value);
						returnResult.setMessage(e.toString());
					}
					return returnResult;
				}
			}
		}
		return returnResult;
	}
	
	
}
